// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.designer.ui.wizards;

import org.dengues.core.components.IComponentsFactory;
import org.dengues.core.resource.DenguesProject;
import org.dengues.core.resource.DenguesProjectFactory;
import org.dengues.designer.ui.DesignerUIPlugin;
import org.dengues.designer.ui.i18n.Messages;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.fieldassist.AutoCompleteField;
import org.eclipse.jface.fieldassist.TextContentAdapter;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf 1 2006-09-29 17:06:40Z qiang.zhang $
 * 
 */
public class NewProjectWizardPage extends WizardPage {

    public static final String MAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*(\\.[_A-Za-z0-9-]+)"; //$NON-NLS-1$

    private DenguesProject[] projects;

    private IStatus nameStatus;

    private IStatus descriptionStatus;

    private IStatus usernameStatus;

    private IStatus useremailStatus;

    /** Name field. */
    private Text nameText;

    /** Description field. */
    private Text descriptionText;

    private Text userNameText;

    private Text userMailText;

    /**
     * Qiang.Zhang.Adolf@gmail.com NewProjectWizardPage constructor comment.
     */
    public NewProjectWizardPage() {
        super("WizardPage"); //$NON-NLS-1$
        setTitle(Messages.getString("NewProjectWizardPage.Title")); //$NON-NLS-1$
        setDescription(Messages.getString("NewProjectWizardPage.Description")); //$NON-NLS-1$
        nameStatus = createOkStatus();
        descriptionStatus = createOkStatus();
        usernameStatus = createOkStatus();
        useremailStatus = createOkStatus();

    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
     */
    public void createControl(Composite parent) {

        Composite container = new Composite(parent, SWT.NONE);

        GridLayout layout = new GridLayout();
        container.setLayout(layout);

        container.setLayoutData(new GridData(GridData.FILL_BOTH));
        projectGroup(container);
        userGroup(container);
        setControl(container);
        addListeners();
        setPageComplete(false);
        checkFieldsValue();
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "projectGroup".
     * 
     * @param container
     */
    private void projectGroup(Composite container) {
        Group container2 = new Group(container, SWT.NONE);
        container2.setText(Messages.getString("NewProjectWizardPage.prj.info")); //$NON-NLS-1$
        container2.setLayout(new GridLayout(2, false));
        container2.setLayoutData(new GridData(GridData.FILL_BOTH));

        // Name
        Label nameLab = new Label(container2, SWT.NONE);
        nameLab.setText(Messages.getString("NewProjectWizardPage.Name")); //$NON-NLS-1$

        nameText = new Text(container2, SWT.BORDER);
        nameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        // Description
        Label descriptionLab = new Label(container2, SWT.NONE);
        descriptionLab.setText(Messages.getString("NewProjectWizardPage.Comment")); //$NON-NLS-1$
        descriptionLab.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));

        descriptionText = new Text(container2, SWT.BORDER);
        GridData data = new GridData(GridData.FILL_HORIZONTAL);
        data.heightHint = 60;
        descriptionText.setLayoutData(data);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "userGroup".
     * 
     * @param container
     */
    private void userGroup(Composite container) {
        Group group = new Group(container, SWT.NONE);
        group.setText(Messages.getString("NewProjectWizardPage.user.info")); //$NON-NLS-1$
        group.setLayout(new GridLayout(2, false));
        group.setLayoutData(new GridData(GridData.FILL_BOTH));

        Label userNameL = new Label(group, SWT.NONE);
        userNameL.setText(Messages.getString("NewProjectWizardPage.userName")); //$NON-NLS-1$
        userNameText = new Text(group, SWT.BORDER);
        userNameText.setLayoutData(new GridData(GridData.FILL_BOTH));
        userNameText.setEditable(true);
        userNameText.setText(IComponentsFactory.DENGUES_DEMOS_USERNAME);
        String[] validUsers = { "tom", "dick", "harry", "ferdinand", "tim", "teresa", "tori", "daniela", "aaron", "kevin", "tod",
                "mike", "kim", "eric", "paul" };
        new AutoCompleteField(userNameText, new TextContentAdapter(), validUsers);

        userNameL = new Label(group, SWT.NONE);
        userNameL.setText(Messages.getString("NewProjectWizardPage.userEmail")); //$NON-NLS-1$
        userMailText = new Text(group, SWT.BORDER);
        userMailText.setLayoutData(new GridData(GridData.FILL_BOTH));
        userMailText.setEditable(true);
        userMailText.setText(IComponentsFactory.DENGUES_DEMOS_EMAIL);
    }

    /**
     * qzhang Comment method "addListeners".
     */
    private void addListeners() {
        nameText.addModifyListener(new ModifyListener() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
             */
            public void modifyText(ModifyEvent e) {
                checkFieldsValue();
            }

        });
        descriptionText.addModifyListener(new ModifyListener() {

            public void modifyText(ModifyEvent e) {
                checkFieldsValue();
            }
        });
        userNameText.addModifyListener(new ModifyListener() {

            public void modifyText(ModifyEvent e) {
                checkFieldsValue();
            }

        });
        userMailText.addModifyListener(new ModifyListener() {

            public void modifyText(ModifyEvent e) {
                checkFieldsValue();
            }

        });
    }

    private void checkFieldsValue() {
        if (nameText.getText().length() == 0) {
            nameStatus = new Status(IStatus.ERROR, DesignerUIPlugin.PLUGIN_ID, IStatus.ERROR, Messages
                    .getString("NewProjectWizardPage.Empty.Label"), null); //$NON-NLS-1$
        } else {
            if (isProjectNameAlreadyUsed(nameText.getText())) {
                nameStatus = new Status(IStatus.ERROR, DesignerUIPlugin.PLUGIN_ID, IStatus.ERROR, Messages
                        .getString("NewProjectWizardPage.Exist.Label"), null); //$NON-NLS-1$
            } else {
                if (userNameText.getText().length() == 0) {
                    usernameStatus = new Status(IStatus.ERROR, DesignerUIPlugin.PLUGIN_ID, IStatus.ERROR, Messages
                            .getString("NewProjectWizardPage.userName.empty"), null); //$NON-NLS-1$
                } else {
                    usernameStatus = createOkStatus();
                    if (userMailText.getText().length() == 0) {
                        useremailStatus = new Status(IStatus.ERROR, DesignerUIPlugin.PLUGIN_ID, IStatus.ERROR, Messages
                                .getString("NewProjectWizardPage.userEmail.empty"), null); //$NON-NLS-1$
                    } else if (!userMailText.getText().matches(MAIL_PATTERN)) {
                        useremailStatus = new Status(IStatus.ERROR, DesignerUIPlugin.PLUGIN_ID, IStatus.ERROR, Messages
                                .getString("NewProjectWizardPage.userEmail.invaild"), null); //$NON-NLS-1$
                    } else {
                        if (descriptionText.getText().length() == 0) {
                            descriptionStatus = new Status(IStatus.WARNING, DesignerUIPlugin.PLUGIN_ID, IStatus.WARNING, Messages
                                    .getString("NewProjectWizardPage.project.empty"), null); //$NON-NLS-1$
                        } else {
                            descriptionStatus = createOkStatus();
                        }
                        useremailStatus = createOkStatus();
                    }
                }
                nameStatus = createOkStatus();
            }
        }
        IStatus findMostSevere = findMostSevere();
        setMessage(findMostSevere);
        setPageComplete(findMostSevere.getSeverity() != IStatus.ERROR);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "setMessage".
     * 
     * @param status
     */
    private void setMessage(IStatus status) {
        if (IStatus.ERROR == status.getSeverity()) {
            setErrorMessage(status.getMessage());
            setMessage(""); //$NON-NLS-1$
        } else if (IStatus.WARNING == status.getSeverity()) {
            setMessage(status.getMessage(), status.getSeverity());
            setErrorMessage(null);
        } else {
            setMessage(status.getMessage(), status.getSeverity());
            setErrorMessage(null);
        }
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "findMostSevere".
     * 
     * @return
     */
    private IStatus findMostSevere() {
        IStatus status;
        if (nameStatus.getSeverity() == IStatus.ERROR) {
            status = nameStatus;
        } else if (descriptionStatus.getSeverity() == IStatus.ERROR) {
            status = descriptionStatus;
        } else if (usernameStatus.getSeverity() == IStatus.ERROR) {
            status = usernameStatus;
        } else if (useremailStatus.getSeverity() == IStatus.ERROR) {
            status = useremailStatus;
        } else {
            status = nameStatus.getSeverity() > descriptionStatus.getSeverity() ? nameStatus : descriptionStatus;
            status = usernameStatus.getSeverity() > status.getSeverity() ? usernameStatus : status;
            status = useremailStatus.getSeverity() > status.getSeverity() ? useremailStatus : status;
            status = descriptionStatus.getSeverity() > status.getSeverity() ? descriptionStatus : status;

        }
        return status;
    }

    private boolean isProjectNameAlreadyUsed(String newProjectName) {
        projects = DenguesProjectFactory.readProjects();
        for (DenguesProject prj : projects) {
            if (newProjectName.toLowerCase().equals(prj.getName().toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    private static IStatus createOkStatus() {
        return new Status(IStatus.OK, DesignerUIPlugin.PLUGIN_ID, IStatus.OK, "you can create the project.", null); //$NON-NLS-1$
    }

    /**
     * Getter for nameText.
     * 
     * @return the nameText
     */
    public String getNameText() {
        return this.nameText.getText();
    }

    /**
     * Getter for descriptionText.
     * 
     * @return the descriptionText
     */
    public String getDescriptionText() {
        return this.descriptionText.getText();
    }

    /**
     * Getter for userNameText.
     * 
     * @return the userNameText
     */
    public String getUserNameText() {
        return this.userNameText.getText();
    }

    /**
     * Getter for userMailText.
     * 
     * @return the userMailText
     */
    public String getUserMailText() {
        return this.userMailText.getText();
    }
}
